package com.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.User;
import com.utils.JsonUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/json")
public class JsonController {

    @RequestMapping("/j1")
    /*@ResponseBody   // 写了RestController 就不用写这个，代表返回的是字符串，不走视图解析器*/
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User(1, "小红", 18);
        String str = mapper.writeValueAsString(user);
        return str;
    }

    @RequestMapping("/j2")
    /*@ResponseBody   // 写了RestController 就不用写这个，代表返回的是字符串，不走视图解析器*/
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        List<User> userList = new ArrayList<>();

        User user1 = new User(1, "小红1", 18);
        User user2 = new User(2, "小红2", 18);
        User user3 = new User(3, "小红3", 18);
        User user4 = new User(4, "小红4", 18);

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        String str = mapper.writeValueAsString(userList);
        return str;
    }

    @RequestMapping("/j3")
    /*@ResponseBody   // 写了RestController 就不用写这个，代表返回的是字符串，不走视图解析器*/
    public String json3() throws JsonProcessingException {
//        ObjectMapper mapper = new ObjectMapper();

        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//        String str = mapper.writeValueAsString(sdf.format(date));
        return JsonUtils.getJson(sdf.format(date));
    }

    @RequestMapping("/j4")
    public String json4() throws JsonProcessingException {

        List<User> userList = new ArrayList<>();

        User user1 = new User(1, "小红1", 18);
        User user2 = new User(2, "小红2", 18);
        User user3 = new User(3, "小红3", 18);
        User user4 = new User(4, "小红4", 18);

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        return JSON.toJSONString(userList);
    }
}
